const puppeteer = require('puppeteer');

async function jdRush(skuId, cookie) {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  // 设置Cookie
  await page.setCookie({
    name: 'your_cookie_name',
    value: cookie,
    domain: '.jd.com',
  });

  // 访问商品页面
  await page.goto(`https://item.jd.com/${skuId}.html`);

  // 自动下单逻辑
  const rushOrder = async () => {
    try {
      // 点击立即购买
      await page.click('#btn-reservation');

      // 提交订单
      await page.waitForSelector('.checkout-submit', { timeout: 5000 });
      await page.click('.checkout-submit');

      return true;
    } catch (error) {
      return false;
    }
  };

  // 轮询检查
  while (true) {
    if (await rushOrder()) {
      console.log('抢单成功！');
      break;
    }
    await page.reload();
    await new Promise((resolve) => setTimeout(resolve, 500));
  }

  await browser.close();
}

// 使用示例
jdRush('123456789', 'your_cookie_value');
